import {
  reqGetCategory1List,
  reqGetCategory2List,
  reqGetCategory3List
} from '@api/category'

const state = {
  // 选中的分类id
  category1Id: '',
  category2Id: '',
  category3Id: '',
  // 展示的分类列表
  category1List: [],
  category2List: [],
  category3List: []
}

const actions = {
  getCategory1List({ commit }) {
    return reqGetCategory1List().then(res => {
      commit('GET_CATEGORY1_LIST', res.data)
    })
  },
  getCategory2List({ commit }, category1Id) {
    return reqGetCategory2List(category1Id).then(res => {
      commit('GET_CATEGORY2_LIST', { category1Id, category2List: res.data })
    })
  },
  getCategory3List({ commit }, category2Id) {
    return reqGetCategory3List(category2Id).then(res => {
      commit('GET_CATEGORY3_LIST', { category2Id, category3List: res.data })
    })
  }
  // setCategory3Id({ commit }, category3Id) {
  //   commit("SET_CATEGORY3_ID", category3Id);
  // }
}

const mutations = {
  GET_CATEGORY1_LIST: (state, category1List) => {
    state.category1List = category1List
  },
  GET_CATEGORY2_LIST: (state, { category1Id, category2List }) => {
    /*
      获取2级分类列表数据：
        1. 请求2级分类列表数据
        2. 清空3级分类列表数据
        3. 清空2级id和3级id
    */
    // 1. 请求2级分类列表数据
    state.category2List = category2List
    state.category1Id = category1Id
    // 2. 清空3级分类列表数据
    state.category3List = []
    // 3. 清空2级id和3级id
    state.category2Id = ''
    state.category3Id = ''
  },
  GET_CATEGORY3_LIST: (state, { category2Id, category3List }) => {
    /*
      获取3级分类列表数据：
        1. 请求2级分类列表数据
        2. 清空3级id
    */
    state.category3List = category3List
    state.category2Id = category2Id
    // 2. 清空3级id
    state.category3Id = ''
  },
  SET_CATEGORY3_ID: (state, category3Id) => {
    state.category3Id = category3Id
  },
  RESET_CATEGORY(state) {
    // 选中的分类id
    state.category1Id = ''
    state.category2Id = ''
    state.category3Id = ''
    // 展示的分类列表
    state.category1List = []
    state.category2List = []
    state.category3List = []
  }
}

export default {
  // 启用命名空间
  // 将来使用actions时需要加上模块名称
  namespaced: true,
  state,
  mutations,
  actions
}
